//
//  FirstDetailViewController.m
//  CloudMD
//
//  Created by apple on 16/2/22.
//  Copyright (c) 2016年 HuaZhengInfo. All rights reserved.
//

#import "FirstDetailViewController.h"
#import "DetailGrabTableViewCell.h"
#import "ImageGrabTableViewCell.h"
#import "ImageTableViewCell.h"
#import "DetailExeViewController.h"
#import "MyOrderDetailModel.h"
#import "ImageModel.h"
#import "ShowInfoViewController.h"
#import "XJAlbum.h"

@interface FirstDetailViewController ()<UITableViewDataSource,UITableViewDelegate>{

    UITableView * _tableView;
    NSMutableArray * _mainArray;
    NSMutableArray * _detailArray;
    NSMutableArray * _dataArray;
    NSMutableArray * _imageArray; //  图片数组
    NSMutableArray *_beforeImageArray;
    NSMutableArray *_laterImageArray;
    MyOrderDetailModel * _model;
    UIButton * _button; // 抢单按钮
}

@property (nonatomic, assign) BOOL picDownload;

@end

@implementation FirstDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 导航栏左按钮
    UIButton * leftButton = [GDFactory creatUIButtonWithFrame:CGRectMake(0, 0, 10, 15) backImage:@"left_arrow" title:nil titleLableColcor:nil titleLabelFont:nil];
    [leftButton addTarget:self action:@selector(clickLeft) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    // 创建导航栏标题
    [self creatTabelViewTitleView];
    
    // 初始化
    _mainArray = [NSMutableArray array];
    _detailArray = [NSMutableArray array];
    _dataArray = [NSMutableArray array];
    _imageArray = [NSMutableArray array];
    _beforeImageArray = [NSMutableArray array];
    _laterImageArray = [NSMutableArray array];
//    _GUID = @"";
//    _ID = @"";
    _SYSCODE = @"";
    
    // 请求列表数据
    [self requestData];
    
    // 请求图片数据
    [self requestImageData];
    
    // 创建UI
    [self buildTableview];
    
    // 刷新
    [self setupRefresh];

}

#pragma mark -- 请求数据
- (void)requestData{
    
    [_dataArray removeAllObjects];
    [_mainArray removeAllObjects];
    [_detailArray removeAllObjects];
    [_imageArray removeAllObjects];
    [_beforeImageArray removeAllObjects];
    [_laterImageArray removeAllObjects];
    
    NSArray * keyArray = @[@"GUID",@"ID",@"SYSCODE"];
    NSArray * valueArray = @[_GUID,_ID,_SYSCODE];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,MyOrderDetail_URL];
//    [SVProgressHUD showWithStatus:@"加载中..."];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * dataDict in array) {
            
            _model = [[MyOrderDetailModel alloc] initWithDict:dataDict];
            [_dataArray addObject:_model];
        }
        
        [self creatGrabButton];
        [_tableView reloadData];
//        [SVProgressHUD dismiss];
    } withTag:101];
    
    _mainArray = [NSMutableArray arrayWithObjects:@"订单号:",@"问题类型:",@"问题区位:",@"问题描述:",@"资料:",@"提报时间:",@"提报人:",@"应完成时间:",@"来源:",@"对象:",@"订单状态:",@"处理前资料:",@"处理后资料:",nil];
    
    
}

#pragma mark -- 请求图片数据
- (void)requestImageData{

    [_imageArray removeAllObjects];
    [_beforeImageArray removeAllObjects];
    [_laterImageArray removeAllObjects];
    NSArray * keyArray = @[@"ID"];
    NSArray * valueArray = @[_ID];
    NSDictionary * dict = [[NSDictionary alloc] initWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,DownloadAttachment_URL];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        NSMutableArray * array = [http.returnArray mutableCopy];
        self.picDownload = YES;
        for (NSDictionary * dataDict in array) {
            
            ImageModel * model = [[ImageModel alloc] initWith:dataDict];
            if ([model.TYPE isEqualToString:@"INSPECTION"]) {
                [_imageArray addObject:model.WSPATH];
            }
            if ([model.TYPE isEqualToString:@"beforeOrderExec"]) {
                [_beforeImageArray addObject:model.WSPATH];
            }
            if ([model.TYPE isEqualToString:@"afterOrderExec"]) {
                [_laterImageArray addObject:model.WSPATH];
            }
        }
        
        [_tableView reloadData];
        NSUserDefaults * imageUser = [NSUserDefaults standardUserDefaults];
        [imageUser setObject:_imageArray forKey:@"IMAGE"];
    } withTag:101];
}

#pragma mark --- 创建TableView
- (void)buildTableview{
    
    _tableView = [[UITableView alloc] init];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [_tableView addGestureRecognizer:tapGesture];
    
    _tableView.rowHeight = SCR_H / 7;
//    CGFloat h = _tableView.rowHeight * _mainArray.count;
    _tableView.frame = CGRectMake(0, 0, SCR_W, SCR_H - 80);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    
    //隐藏分割线
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}

- (void)handleTap:(UITapGestureRecognizer *)tap {
    CGPoint tapLocation = [tap locationInView:_tableView];
    NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:tapLocation];
    if (indexPath.row == 4) {
        ImageTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
        CGPoint pointInCell = [tap locationInView:cell];
        for (UIView *view in cell.contentView.subviews) {
            if (CGRectContainsPoint(view.frame, pointInCell)) {
                if (_imageArray.count > 0) {
                    [self showImageWithArray:_imageArray currentPage:view.tag];
                }
            }
        }
    }
    if (indexPath.row == 11) {
        ImageTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
        CGPoint pointInCell = [tap locationInView:cell];
        for (UIView *view in cell.contentView.subviews) {
            if (CGRectContainsPoint(view.frame, pointInCell)) {
                if (_beforeImageArray.count > 0) {
                    [self showImageWithArray:_beforeImageArray currentPage:view.tag];
                }
            }
        }
    }
    if (indexPath.row == 12) {
        ImageTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
        CGPoint pointInCell = [tap locationInView:cell];
        for (UIView *view in cell.contentView.subviews) {
            if (CGRectContainsPoint(view.frame, pointInCell)) {
                if (_laterImageArray.count > 0) {
                    [self showImageWithArray:_laterImageArray currentPage:view.tag];
                }
            }
        }
    }
}



- (void)creatGrabButton{

    UIView * footView = [GDFactory creatUIViewWithFrame:CGRectMake(0, 0, SCR_W, 40) backColor:[UIColor clearColor]];
    _tableView.tableFooterView = footView;
    // 抢单按钮
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(SCR_W/4, 0, SCR_W/2, 40)];
//    button.center = footView.center;
    [button setBackgroundImage:[UIImage imageNamed:@"3在线下单"] forState:UIControlStateNormal];
    
    NSString * state = _model.ORDERSTATUS;
    if ([state isEqualToString:@"已完成"]) {
        
        button.hidden = YES;
//        [button setTitle:@"订单已完成" forState:UIControlStateNormal];
    }else{
        
        button.hidden = NO;
        [button setTitle:@"订单完成" forState:UIControlStateNormal];
    }
    
    [button addTarget:self action:@selector(clickGrab:) forControlEvents:UIControlEventTouchUpInside];
    
    [footView addSubview:button];

    
}

#pragma mark -- 创建导航栏标题
- (void)creatTabelViewTitleView{
    
    UIView * titleView = [GDFactory creatUIViewWithFrame:CGRectMake(0, 0, 80, 45) backColor:[UIColor clearColor]];
    UILabel * mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, titleView.frame.size.height)];
    mainLabel.textAlignment = NSTextAlignmentCenter;
    mainLabel.text = @"订单详情";
    mainLabel.textColor = [UIColor whiteColor];
    mainLabel.font = [UIFont systemFontOfSize:18];
    [titleView addSubview:mainLabel];
    
    self.navigationItem.titleView = titleView;
    
}

#pragma mark -- TableViewDelegate And dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([_model.ORDERSTATUS isEqualToString:@"已完成"]) {
        return _mainArray.count;
    } else {
        return _mainArray.count-2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 4 || indexPath.row == 11 || indexPath.row == 12) {
        NSString * ID = @"cell";
        ImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        
        if (cell == nil) {
            cell = [[ImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//            cell.imageArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"IMAGE"];
        }
        if (self.picDownload) {
            if (indexPath.row == 4) {
                cell.imageArray = _imageArray;
                cell.label.text = @"资料:";
            }
            if (indexPath.row == 11) {
                cell.imageArray = _beforeImageArray;
                cell.label.text = @"处理前资料:";
            }
            if (indexPath.row == 12) {
                cell.imageArray = _laterImageArray;
                cell.label.text = @"处理后资料:";
            }
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
        
    }else{
        NSString * ID = @"cellId";
        DetailGrabTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[DetailGrabTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            
        }
        cell.mainLabel.text = _mainArray[indexPath.row];
        if (indexPath.row == 0) {
            cell.detailLabel.text = _model.SYSCODE;
        }
        if (indexPath.row == 1) {
            cell.detailLabel.text = _model.TYPE_NAME;
        }
        if (indexPath.row == 2) {
            cell.detailLabel.text = _model.GRID_NAME;
        }
        if (indexPath.row == 3) {
            cell.detailLabel.text = _model.REMARK;
            CGSize maximumLabelSize = CGSizeMake(SCR_W - 20, 1000);
            CGSize expectSize = [cell.detailLabel sizeThatFits:maximumLabelSize];
            cell.detailLabel.frame = CGRectMake(10, CGRectGetMaxY(cell.mainLabel.frame)+10, SCR_W-20, expectSize.height);
        }
        if (indexPath.row == 5) {
            cell.detailLabel.text = _model.DATE;
        }
        if (indexPath.row == 6) {
            cell.detailLabel.text = _model.USER_NAME;
        }
        if (indexPath.row == 7) {
            cell.detailLabel.text = _model.PLAN_DATE;
        }
        if (indexPath.row == 8) {
            cell.detailLabel.text = _model.SOURCE_NAME;
        }
        if (indexPath.row == 9) {
            cell.detailLabel.text = _model.OBJECT_NAME;
        }
        if (indexPath.row == 10) {
            cell.detailLabel.text = _model.STATE;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 3) {
        UILabel *tmpLabel = [[UILabel alloc] init];
        tmpLabel.font = [UIFont systemFontOfSize:18];
        tmpLabel.numberOfLines = 0;
        tmpLabel.lineBreakMode = NSLineBreakByCharWrapping;
        tmpLabel.text = _model.REMARK;
        CGSize maximumLabelSize = CGSizeMake(SCR_W - 20, 1000);
        CGSize expectSize = [tmpLabel sizeThatFits:maximumLabelSize];
        return SCR_H/9 * 0.4 + expectSize.height + 10;
    }
    if (indexPath.row == 4) {
        if (_imageArray.count < 6) {
            return SCR_H / 5;
        } else {
            return SCR_H * 0.33;
        }
    }
    if (indexPath.row == 11) {
        if (_beforeImageArray.count < 6) {
            return SCR_H / 5;
        } else {
            return SCR_H * 0.33;
        }
    }
    if (indexPath.row == 12) {
        if (_laterImageArray.count < 6) {
            return SCR_H / 5;
        } else {
            return SCR_H * 0.33;
        }
    }
    return SCR_H / 9;

}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//
//    if (indexPath.row == 4 || indexPath.row == 11 || indexPath.row == 12) {
////            ShowInfoViewController * showInfoVC = [[ShowInfoViewController alloc] init];
////            if (indexPath.row == 4) {
////                showInfoVC.imageArray = _imageArray;
////            }
////            if (indexPath.row == 11) {
////                showInfoVC.imageArray = _beforeImageArray;
////            }
////            if (indexPath.row == 12) {
////                showInfoVC.imageArray = _laterImageArray;
////            }
////            [self.navigationController pushViewController:showInfoVC animated:YES];
//            if (_imageArray.count > 0 && indexPath.row == 4) {
//                [self showImageWithArray:_imageArray];
//            }
//            if (_beforeImageArray.count > 0 && indexPath.row == 11) {
//                [self showImageWithArray:_beforeImageArray];
//            }
//            if (_laterImageArray.count > 0 && indexPath.row == 12) {
//                [self showImageWithArray:_laterImageArray];
//            }
//
//    }
//}

- (void)showImageWithArray:(NSArray *)array currentPage:(NSInteger)page {
    XJAlbum *imageShowVC = [[XJAlbum alloc] initWithImgUrlArr:array CurPage:page];
    imageShowVC.photoFrame = CGRectMake(0, 0, SCR_W, SCR_H);
    [self.navigationController presentViewController:imageShowVC animated:YES completion:nil];
}

#pragma mark -- 点击完成
- (void)clickGrab:(UIButton *)button{
    
    NSString * ORDERSTATUS = _model.ORDERSTATUS;
    if ([ORDERSTATUS isEqualToString:@"已完成"]) {
        
        button.userInteractionEnabled = NO;
        
    }else{
    DetailExeViewController * detailVC = [[DetailExeViewController alloc] init];
     detailVC.GUID = _model.GUID;
     detailVC.ID = _model.ID;
    [self.navigationController pushViewController:detailVC animated:YES];
    }
}


#pragma mark -- 刷新
- (void)setupRefresh{

//    [_tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    
}

- (void)headerRefreshing{

//    [_tableView headerEndRefreshing];
    [self requestData];
}

#pragma mark -- clickLeft
- (void)clickLeft{

    [self.navigationController popViewControllerAnimated:YES];
}

@end
